package cn.itcast.gateway.filters;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 */
@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    /**
     * 需求 ：请求参数中带有token 内容，就放行，否则提示未授权
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("自定义全局过滤器-执行-----");
        //判断请求参数中是否带token，没有就返回403状态码
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取token参数
        String token = request.getQueryParams().getFirst("token");

        //判断token是否优质
        if (StringUtils.isNotBlank(token)) {
            //token不为空，放行
            return chain.filter(exchange);
        } else {
            //token为空，返回403
            response.setStatusCode(HttpStatus.FORBIDDEN);
            //直接返回浏览器
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
